package tmt.usercenter.web.domain;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.voodoodyne.jackson.jsog.JSOGGenerator;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import tmt.usercenter.web.domain.enums.FuncPointType;
import tmt.usercenter.web.domain.enums.SmStatus;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;

/**
 * 短信历史记录。
 */
@Getter
@Setter
@Entity
@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler","fieldHandler"})
@EntityListeners({AuditingEntityListener.class})
@JsonIdentityInfo(generator = JSOGGenerator.class)
public class SmHistory extends BaseCreator implements Serializable {

    /**
     * 接收手机号码
     */
    private String toMobile;

    /**
     * 发送内容
     */
    private String content;

    /**
     * 短信发送平台
     */
    private String sender;

    /**
     * 短信状态
     */
    @Enumerated(EnumType.STRING)
    private SmStatus smStatus = SmStatus.NOT_SEND;

    /**
     * 期望发送的时间
     */
    @Temporal(TemporalType.TIMESTAMP)
    private Date sendTime = null;

    /**
     * 发送结果
     */
    private String sendResult;

    /**
     * 结果接收时间。
     */
    @Temporal(TemporalType.TIMESTAMP)
    private Date resultReceivedTime = null;

    /**
     * 发送短信的功能点
     */
    @Enumerated(EnumType.STRING)
    private FuncPointType funcPoint = FuncPointType.USER_REGISTER;


    @ManyToOne(cascade = {CascadeType.REFRESH}, fetch = FetchType.LAZY)
    @JoinColumn(name="originSystem_id")
    private ClientSystem originSystem;

    /**
     * 是否已经被使用过了
     */
    private boolean valid = false;

    /**
     * 获得短信历史记录
     * @param mobile
     * @param content
     * @param sender
     * @param smStatus
     * @param originResult
     * @param clientSystem
     * @return
     */
    public static SmHistory newInstance(String mobile, String content,
                                                      String sender, Date sendTime, String originResult, FuncPointType funcPoint,
                                                      SmStatus smStatus, ClientSystem clientSystem, boolean valid, boolean isSync){
        SmHistory smHistory = new SmHistory();
        smHistory.setToMobile(mobile);
        smHistory.setContent(content);
        smHistory.setSender(sender);
        smHistory.setSendTime(isSync ? new Date() : sendTime);
        smHistory.setResultReceivedTime(isSync ? new Date() : null);
        smHistory.setSendResult(isSync ? originResult : null);
        smHistory.setResultReceivedTime(isSync ? new Date() : null);
        smHistory.setFuncPoint(funcPoint);
        smHistory.setSmStatus(smStatus);
        smHistory.setValid(valid);
        smHistory.setOriginSystem(clientSystem);
        return smHistory;
    }

}
